const jwt = require('jsonwebtoken');
const { promisify } = require('util');
const tokenService = require('../services/tokenService');

const authMiddleware = async (ctx, next) => {
    const token = ctx.headers['authorization']?.split(' ')[1];

    if (!token) {
        ctx.status = 401;
        ctx.body = { message: 'No token provided' };
        return;
    }

    try {
        const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
        ctx.state.user = decoded;
        await next();
    } catch (error) {
        ctx.status = 401;
        ctx.body = { message: 'Invalid token' };
    }
};

module.exports = authMiddleware;